<template>
  <div class="layout-wrapper layout-witness">
    <div class="layout-header layout-search">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-button type="primary" @click="initRoom()" :loading="btnLoading"> 房间初始化 </el-button>
        </el-form-item>
        <el-form-item class="rigthText">
          <el-select
            v-model="searchForm.roomtype"
            class="ui-w320"
            option-max-width="180px"
            placeholder="房间类型"
            clearable
            @change="handleSearchFn()"
          >
            <!-- <el-option key label="全部" value></el-option> -->
            <el-option v-for="item in roomtype" :key="item" :label="item" :value="item" />
          </el-select>
          <el-input
            v-model.trim="searchForm.keywords"
            class="ui-w320"
            placeholder="房间名称"
            @keyup.native.enter="handleSearchFn()"
          >
            <el-button slot="append" type="primary" icon="icon-sousuo" @click="handleSearchFn()" />
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="layout-body">
      <el-table ref="taskTable" v-loading="tableLoading" :data="tableData" height="100%" stripe>
        <el-table-column type="index" align="left" label="序号" width="50">
          <template slot-scope="scope">
            {{ pageObj.currentPage * pageObj.pageSize + 1 + scope.$index }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="房间名称" min-width="200" />
        <el-table-column prop="roomtype" label="房间类型" min-width="200" />
        <el-table-column prop="location" label="房间位置" min-width="200" />
        <el-table-column prop="describeinfo" label="描述" min-width="200" />
        <el-table-column label="操作" align="left" header-align="center" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="default" @click="viewDate(scope.row)"> 查看 </el-button>
            <el-button type="text" size="default" @click="updateDate(scope.row)"> 修改 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="layout-footer">
      <wpagination
        v-if="pageObj.total > pageObj.pageSizes[0]"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :pageSizes="pageObj.pageSizes"
        @pagination="projectListFn()"
      />
    </div>
    <!-- 编辑弹框 -->
    <el-dialog
      width="60%"
      :close-on-click-modal="false"
      draggable
      :show-close="false"
      title="房间信息"
      :visible.sync="editRoom"
    >
      <div>
        <el-form ref="roomForm" :model="roomForm" :rules="roomRules" label-width="auto">
          <el-form-item label="房间名称" prop="name">
            <el-input
              v-model="roomForm.name"
              placeholder="请输入房间名称"
              disabled
            />
          </el-form-item>
          <el-form-item label="房间类型" prop="roomtype">
            <el-select
              v-model="roomForm.roomtype"
              style="width: 100%"
              filterable
              disabled
            >
              <!-- @change="typeChange" -->
              <el-option v-for="item in roomtype" :key="item" :value="item" :label="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="房间位置" prop="location">
            <el-input
              v-model="roomForm.location"
              placeholder="请输入房间位置"
              disabled
            />
          </el-form-item>
          <el-form-item label="房间描述信息" prop="describeinfo">
            <el-input
              v-model="roomForm.describeinfo"
              type="textarea"
              :rows="2"
              placeholder="请输入房间描述信息"
              show-word-limit
              :disabled="childType == 'view' ? true : false"
            />
          </el-form-item>
          <el-form-item label="关联设备" prop="location" v-if="childType == 'view'"> </el-form-item>
          <div class="layout-body" v-if="childType == 'view'">
            <el-table v-loading="tableLoading" :data="deviceData" height="100%" stripe>
              <el-table-column type="index" align="left" label="序号" width="50">
                <template slot-scope="scope">
                  {{ 1 + scope.$index }}
                </template>
              </el-table-column>
              <el-table-column prop="devicename" label="设备名称" min-width="200" />
              <el-table-column prop="devicecode" label="设备编号" min-width="200" />
              <el-table-column prop="devicetype" :formatter="formatterDevicetype" label="设备类型" min-width="200" />
              <el-table-column prop="ip" label="设备IP" min-width="200" />
<!--              <el-table-column label="操作" align="left" header-align="center" width="200">
                <template slot-scope="scope">
                  <el-button type="text" size="default" @click="viewDate(scope.row)"> 查看 </el-button>
                </template>
              </el-table-column>-->
            </el-table>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="childType != 'view'" :loading="btnLoading" type="primary" @click="submitRoom('roomForm')"
          >确定</el-button
        >
        <el-button @click="cancel('roomForm')">取消</el-button>
      </span>
    </el-dialog>
    <!-- 设备关联 -->
    <el-dialog
      width="70%"
      :close-on-click-modal="false"
      draggable
      :show-close="false"
      title="设备关联"
      :visible.sync="roomDeviceShow"
    >
      <device
        :roomid="roomForm.id"
        @close="cancelDevice"
      />
    </el-dialog>
  </div>
</template>

<script>
  // 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  import { list, edit, deviceList, initRoom} from "../../../../../api/weeon/room";
  // import ProjectDetailsDialog from "../../../../../components/dialog/ProjectDetailsDialog.vue";
  import device from "../../components/managementSubsystem/roomManage/deviceList.vue";
  export default {
    // 引入组件
    components: { device },
    props: {},
    data() {
      // 这里存放数据
      return {
        childType: "",
        editRoom: false,
        btnLoading: false,
        roomDeviceShow: false,
        searchForm: {
          roomtype: [""],
          //industrySecondLevel: [], // 选中的行业类别的二级菜单的数组集合
          // tenderMode: "",
          // zsType: "",
          keywords: ""
        },
        roomtype: ["开标室", "评标室", "抽签室", "资格审查评审室", "资格审查接收室"], // 后端返回的所有下拉映射值数据
        tableData: [],
        deviceData: [],
        tableLoading: false,
        pageObj: {
          total: 0,
          currentPage: 0,
          pageSize: 10,
          pageSizes: [10, 20, 30]
        },
        roomForm: {},
        roomRules: {
          name: [{ required: true, message: "请输入房间名称", trigger: "blur" }],
          location: [{ required: true, message: "请输入房间位置", trigger: "blur" }],
          roomtype: [{ required: true, message: "请选择房间类型", trigger: "change" }]
        },
        devicetype: {
          "IPBS":"IP 广播音箱",
          "IPCT":"IP 呼叫终端",
          "CAMERA":"监控",
          "PC":"评标电脑",
          "MIC":"麦克风",
        },
      };
    },
    // 监听属性 类似于data概念
    computed: {},
    // 监控data中的数据变化
    watch: {},
    // 生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.projectListFn();
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    // 生命周期 - 销毁之前
    beforeDestroy() {},
    // 生命周期 - 销毁完成
    destroyed() {},
    // 如果页面有keep-alive缓存功能，这个函数会触发
    activated() {},
    // 方法集合
    methods: {
      // 搜索查询
      handleSearchFn() {
        this.pageObj.total = 0;
        this.pageObj.currentPage = 0;
        this.projectListFn();
      },
      // 数据列表
      async projectListFn() {
        try {
          this.tableLoading = true;
          this.tableData = [];
          // let industryTypeList = [];
          // let industryList = [];
          let params = {
            // industryTypeList, // 行业类型
            // industryList,
            // tenderMode: this.searchForm.tenderMode,
            roomtype: this.searchForm.roomtype,
            keywords: this.searchForm.keywords,
            pageNo: this.pageObj.currentPage,
            pageSize: this.pageObj.pageSize
          };
          const res = await list(params);
          this.tableLoading = false;
          if (res.stat === 1) {
            if (res.data.page.totalElements === 0 && this.pageObj.currentPage !== 0) {
              this.pageObj.currentPage = 0;
              this.$nextTick(() => {
                this.projectListFn();
              });
              return;
            }

            this.tableData = res.data.page.content;
            console.log(this.tableData, "-------------------1");
            this.pageObj.total = res.data.page.totalElements;
          } else {
            this.$message({
              type: "error",
              message: res.msg || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          console.log(error);
          this.tableLoading = false;
        }
      },

      //修改操作
      updateDate(row) {
        this.editRoom = true;
        this.roomForm = row;
        this.childType = "edit";
      },
      //查看操作
      viewDate(row) {
        this.editRoom = true;
        this.roomForm = row;
        this.childType = "view";
        this.getDeviceList();
      },
      //设备关联
      // deviceAss(row) {
      //   this.roomForm = row;
      //   this.roomDeviceShow = true;
      // },
      //获取设备列表
      async getDeviceList() {
        this.tableLoading = true;
        let params = {
          roomid: this.roomForm.roomid
        };
        const res = await deviceList(params);
        this.tableLoading = false;
        if (res.stat === 1) {
          console.log(res.data);
          this.deviceData = res.data;
        } else {
          this.$message({
            type: "error",
            message: res.msg || "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      //取消
      cancelDevice() {
        this.roomDeviceShow = false;
      },
      //取消
      cancel(formName) {
        this.editRoom = false;
        this.tableLoading = false;
        this.roomDeviceShow = false;
        if (this.childType !== "view"){
          this.projectListFn();
        }
        this.childType = "";
      },
      //保存修改
      submitRoom(formName) {
        try {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.doEdit();
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        } catch (error) {
          console.error(error);
          this.$message({
            type: "warning",
            message: "获取数据失败，稍后再试"
          });
        }
      },
      //保存
      async doEdit() {
        this.btnLoading = true;
        const res = await edit(this.roomForm);
        if (res.stat === 1) {
          this.$message({
            type: "success",
            message: "修改成功",
            single: true
          });
        } else {
          this.$message({
            type: "warning",
            message: res.msg,
            single: true
          });
        }
        this.btnLoading = false;
        this.editRoom = false;
        this.childType = "";
        this.$refs.roomForm.resetFields(); //清空对象
        this.projectListFn(); //刷新列表
      },
      //初始化房间
      initRoom(){
        this.$confirm("初始化房间会将当前的数据全部格式化，并重新加载，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.initR();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消操作",
              single: true
            });
          });
      },
      //初始化
      async initR(){
        try {
          this.btnLoading = true;
          this.tableLoading = true;
          const res = await initRoom();
          this.btnLoading = false;
          this.tableLoading = false;
          if (res.stat === 1) {
            this.$message({
              type: "success",
              message: "初始化成功",
              single: true
            });
            this.projectListFn();
          } else {
            this.$message({
              type: "error",
              message: res.msg || "初始化失败",
              single: true
            });
          }
        } catch (error) {
          console.error(error);
          this.btnLoading = false;
          this.tableLoading = false;
        }
      },
      //格式化设备类型
      formatterDevicetype(row, col, val){
        console.log(val);
        let str = "";
        if (val) {
          str = this.devicetype[val];
        }
        return str;
      },
    }
  };
</script>
<style lang="scss" scoped>
  .witness-result {
    width: 76px;
    height: 20px;
    line-height: 20px;
    background: #fc9306;
    border-radius: 10px;
    color: #fff;
    font-size: 12px;
    text-align: center;
  }
  .rigthText {
    padding-right: 10px;
    float: right;
    // margin-left: 460px !important;
  }
</style>
